package view;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeMap;
import info.clearthought.layout.TableLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;
import model.Contato;
import client.Cliente;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class JanelaDoCliente extends javax.swing.JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JLabel labelSaudacao;
	private JLabel labelNomeUsuario;
	private JMenu jMenu1;
	private JMenuItem menuSair;
	private JMenuBar menuJanela;
	private JList listaDeContatos;
	private Cliente cliente;
	private TreeMap<String, Contato> contatosOnline;
	/**
	* Auto-generated main method to display this JFrame
	*/
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				JanelaDoCliente inst = new JanelaDoCliente();
				inst.setLocationRelativeTo(null);
				inst.setVisible(true);
			}
		});
	}

	private JanelaDoCliente(){
		super();
		initGUI();
		cliente = new Cliente(this);
		contatosOnline = new TreeMap<String, Contato>();
		//instancia um dialogo que pega login e senha
		DialogoLogin d = new DialogoLogin(this);
		//fecha o Dialog
		d.dispose();
		labelNomeUsuario.setText(cliente.getUsuario().getNome());
	}
	
	
	private void initGUI() {
		try {
			setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
			TableLayout thisLayout = new TableLayout(new double[][] {{TableLayout.FILL, 27.0, TableLayout.FILL, TableLayout.FILL}, {26.0, 36.0, TableLayout.FILL, TableLayout.FILL}});
			thisLayout.setHGap(5);
			thisLayout.setVGap(5);
			getContentPane().setLayout(thisLayout);
			this.setTitle("iMSN - Comunicação");
			{
				menuJanela = new JMenuBar();
				setJMenuBar(menuJanela);
				menuJanela.setFont(new java.awt.Font("Arial",1,10));
				menuJanela.setName("Menu");
				{
					jMenu1 = new JMenu();
					menuJanela.add(jMenu1);
					jMenu1.setText("Arquivo");
					jMenu1.setPopupMenuVisible(false);
					jMenu1.setName("Arquivo");
					{
						menuSair = new JMenuItem();
						jMenu1.add(menuSair);
						menuSair.setText("Sair");
						menuSair.addActionListener(new ActionListener() {
							
							@Override
							public void actionPerformed(ActionEvent e) {
								// TODO Auto-generated method stub
								fechaJanela();
							}
						});
					}
				}
			}
			{
				labelSaudacao = new JLabel();
				getContentPane().add(labelSaudacao, "0, 0");
				labelSaudacao.setText("Seja Bem-Vindo: ");
				labelSaudacao.setFont(new java.awt.Font("Arial",3,16));
				labelSaudacao.setHorizontalAlignment(SwingConstants.CENTER);
			}
			{
				ListModel listaDeContatosModel = 
					new DefaultComboBoxModel(new String[] {""});
				listaDeContatos = new JList();
				getContentPane().add(listaDeContatos, "0, 1, 3, 3");
				listaDeContatos.setModel(listaDeContatosModel);
				listaDeContatos.addMouseListener(new MouseAdapter() {
					
					@Override
					public void mouseClicked(MouseEvent e) {
						// TODO Auto-generated method stub
						super.mouseClicked(e);
						//se clicou duas vezes
						 if(e.getClickCount() == 2) {
					         Contato contato = contatosOnline.get(listaDeContatos.getSelectedValue()); 
							 trataContatoSelecionado(contato);							 
						 }
					}
				});

			}
			{
				labelNomeUsuario = new JLabel();
				getContentPane().add(labelNomeUsuario, "2, 0, 3, 0");
			}

			this.addWindowListener(new WindowAdapter() {
				
				@Override
				public void windowClosing(WindowEvent e) {
					// TODO Auto-generated method stub
					super.windowClosing(e);
					fechaJanela();
				}
				
			});
					
			pack();
			this.setSize(548, 463);
		} catch (Exception e) {
		    //add your error handling code here
			e.printStackTrace();
		}
	}
	
	  public void atualizaContatos() {
          //atualiza a lista
		  Set<Contato> contatos = cliente.getContatosOnline().keySet();
		  String[] stringContatos = null;
		  stringContatos = adiocionaContaMapeado(contatos);  
          listaDeContatos.removeAll();
          listaDeContatos.setModel(new DefaultComboBoxModel(stringContatos));
  }
  		
	private String[] adiocionaContaMapeado(Set<Contato> contatos){
		String[] stringContatos;
		ArrayList<String> aux = new ArrayList<String>();
		String str = null;
		
		int i = 0;
		for (Object c : contatos) {
			str = (((Contato)c).getNome() + "  -  " + ((Contato)c).getLogin());
			aux.add(str);
			contatosOnline.put(str, (Contato) c);
			i++;
		}
		
		stringContatos = new String[i];
		for (int j = 0; j < stringContatos.length; j++) {
			stringContatos[j] = aux.get(j);
		}
		
		return stringContatos;
		
	}
	
	private void trataContatoSelecionado(Contato c){
		if ( ( cliente.getConversas().get( cliente.getContatosOnline().get(c) )) == null ){
			//Cria janela de conversa
			System.out.println(c.getNome());
			JanelaDeConversa janelaConversa = new JanelaDeConversa(c, cliente.getContatosOnline().get(c));
			//Adiciona a conversa nas conversas do cliente.
			cliente.addConversa(cliente.getContatosOnline().get(c), janelaConversa);
		}
		else
			(cliente.getConversas().get(cliente.getContatosOnline().get(c))).setVisible(true);
			
	}
		
	private void fechaJanela(){
		int resposta = 0;
		resposta = JOptionPane.showConfirmDialog(JanelaDoCliente.this, "Deseja realmente se deslogar?", 
				"Sair da Conversa", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
		
		if (resposta == JOptionPane.YES_OPTION){
			JanelaDoCliente.this.setVisible(false);
			try {
				cliente.solicitaLogout();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (ClassNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (CloneNotSupportedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			System.exit(0);
		}
	}
	
	public Cliente getCliente(){
		return cliente;
	}


}
